<template>
  <div class="department-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="upLoad()">导入excel</el-button>
          <el-button type="danger" size="small" @click="downLoad">导出excel</el-button>
          <el-button type="primary" size="small" @click="hAdd()">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 1.定义需要根据字段排序的字段名称 -->
      <el-card style="margin-top: 10px;" :default-sort="{prop: 'workNumber'}">
        <el-table border :data="list">
          <el-table-column label="头像">
            <template slot-scope="scope">
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              类型：{{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <!-- 2.保证字段列上声明了prop属性 和 sortable属性 -->
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="look(scope.row.id)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <div style="height: 60px; margin-top: 10px">
            <!-- 分页 -->
            <el-pagination
              layout="total, sizes,prev, pager, next, jumper"
              :total="total"
              :page-size="size"
              :current-page="page"
              :page-sizes="[2,5,10]"
              @current-change="hCurrentChange"
              @size-change="hSizeChange"
            />
          </div>
        </el-row>
      </el-card>
      <el-dialog
        title="新增"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
      >
        <addorEdit v-if="showDialog" @close="CAdd" @add="Add" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
function formatData(list) {
  const hireTypEnmu = { 1: '正式', '2': '非正式' }
  const map = {
    'id': '编号',
    'password': '密码',
    'mobile': '手机号',
    'username': '姓名',
    'timeOfEntry': '入职日期',
    'formOfEmployment': '聘用形式',
    'correctionTime': '转正日期',
    'workNumber': '工号',
    'departmentName': '部门',
    'staffPhoto': '头像地址'
  }
  console.log(list)
  let header = []
  // header = ['id', 'mobile', 'username', .....]
  // data = [
  //     ['65c2', '1380000002', '管理员', ....],
  //     ['65c3', '1380000003', '孙财', ....],
  // ]
  let data = []
  // 开始代码
  // 找到一个元素
  const one = list[0]
  if (!one) {
    return { header, data }
  }
  header = Object.keys(one).map(key => {
    return map[key]
  })

  // data把list中每一个对象转成 对应的value数组
  data = list.map(obj => {
    // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
    const key = obj['formOfEmployment'] // 1, 2
    obj['formOfEmployment'] = hireTypEnmu[key] // hireTypEnmu:{1:'正式', '2':'非正式' }

    return Object.values(obj)
  })
  return { header, data }
}

import { getEmployeeList, delEmployee } from '@/api/employees'
import employees from '@/constant/employees'
import addorEdit from './empDialog.vue'
export default {
  components: {
    addorEdit
  },
  data() {
    return {
      list: [],
      page: 1, // 当前页码
      size: 5, // 每页几条
      total: 0, // 总共数据条数
      showDialog: false // 弹框
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 加载员工数据
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log(res)
        res.data.rows.forEach(item => {
          item.timeOfEntry = item.timeOfEntry.replace('T16:00:00.000Z', '')
        }
        )
        this.list = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    },
    // 从hireType中 通过id找到对应的元素的value
    formatEmployment(num) {
      const item = employees.hireType.find(it => it.id === num)
      if (item) {
        return item.value
      } else {
        return '不能确定'
      }
    },
    // 会自动接收当前点击的页码
    hCurrentChange(curPage) {
      // alert(curPage)
      // 1. 更新页码
      this.page = curPage
      // 2. 重发请求
      this.loadEmployeeList()
    },
    // 每页几条
    hSizeChange(curSize) {
      // alert(size)
      // 1. 更新每页的条数
      this.size = curSize
      // 2. 重发请求
      this.loadEmployeeList()
    },
    // 删除数据
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log('删除成功', res)
        if (this.list.length === 1) {
          this.page--
          if (this.page < 1) {
            this.page = 1
          }
        }
        // 重发请求
        this.loadEmployeeList()
      } catch (err) {
        console.log('删除失败', err)
      }
    },
    hDel(id) {
      console.log(id)
      this.$confirm('确认删除吗？').then(() => {
        this.doDel(id)
      }).catch(() => {})
    },
    // 开启对话框
    hAdd() {
      this.showDialog = true
    },
    // 关闭对话框
    CAdd() {
      this.showDialog = false
    },
    // 子组件通知父组件渲染页面
    Add() {
      this.page = Math.ceil(++this.total / this.size)
      this.loadEmployeeList()
    },
    // excel文档导入
    upLoad() {
      this.$router.push('/employees/importance')
    },
    // 文档导出
    downLoad() {
      import('@/vendor/Export2Excel').then(async excel => {
        // 发ajax请求，获取数据
        const res = await getEmployeeList(this.page, this.size)
        const list = res.data.rows
        console.log('从后端获取的数据', list)

        const { header, data } = formatData(list)
        // excel表示导入的模块对象
        console.log(header, data)
        excel.export_json_to_excel({
          // header: ['姓名', '工资'], // 表头 必填
          header: header, // 表头 必填
          data: data,
          // data: [
          //   ['刘备11111111111111', 100],
          //   ['关羽', 500]
          // ], // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    look(id) {
      this.$router.push('/employees/detail/' + id)
    }
  }
}
</script>
